import router from '@/router';
import axios from 'axios';
const host =
  import.meta.env.VITE_IS_REQUEST_PROXY === 'true'
    ? ''
    : import.meta.env.VITE_BASE_API;

const instance = axios.create({
  baseURL: host,
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 可添加 token
    const token = localStorage.getItem('token');
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);

// 添加响应拦截器<>
instance.interceptors.response.use(
  async (response) => {
    if (response.config.responseType === 'blob') {
      return response.data;
    } else if (response.data.code === 1) {
      return response.data.data;
    } else if (response.data.code === 1003) {
      await router.push('/login');
    } else {
      throw Error(`${response.data.msg}`);
    }
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);

export default instance;
